package com.landray.util;

import com.landray.kmss.km.review.webservice.AttachmentForm;
import org.springframework.beans.factory.annotation.Value;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description OA流程工具
 * @Author ych
 * @Date 2020-04-01
 */
public class OAProcessUtils {

    @Value("${hssrm.file-upload-path}")
    private static String fileUploadPath;

    /**
     * 创建附件列表
     *
     * @Param list
     */
    public static List<AttachmentForm> createAllAtts(List<Map<String, String>> list) {

        List<AttachmentForm> attForms = new ArrayList<>();

        list.forEach(item -> {
            try {
                attForms.add(createAtt(item));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return attForms;
    }

    /**
     * 创建附件对象
     *
     * @Param map 包含文件名、附件控件id
     */
    public static AttachmentForm createAtt(Map<String, String> map) throws Exception {
        AttachmentForm attForm = new AttachmentForm();
        String fileName = map.get("fileName").substring(map.get("fileName").lastIndexOf("/")+1);
        attForm.setFdFileName(fileName);
        // 设置附件关键字，表单模式下为附件控件的id
        attForm.setFdKey(map.get("fd_fileId"));

        DataHandler data = file2bytes(fileUploadPath + map.get("fileName"));
        attForm.setFdAttachment(data);

        return attForm;
    }

    /**
     * 将文件转换为字节编码
     */
    public static DataHandler file2bytes(String fileName) throws Exception {
        DataSource dataSource = new FileDataSource(new File(fileName));
        DataHandler dataHandler = new DataHandler(dataSource);
        return dataHandler;
    }
}
